<?php

namespace app\admin\controller;

use app\common\model\AdminModel as models;
use app\common\model\PayWithdraw;
use app\common\model\PayRecharge;
use app\common\model\User;
use app\common\traites\PublicCrudTrait;
use app\validate\Admin;
use think\exception\ValidateException;
use think\facade\Db;

class Index extends Base
{
    protected $model;
    use PublicCrudTrait;
    /**
     * 后台用户控制器
     */
    public function initialize()
    {
        $this->model = new models();
        parent::initialize(); // TODO: Change the autogenerated stub
    }



    //获取列表信息
    public function index()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件
        $post= array_filter($this->request->post());
        $map=[];
        isset($post['user_name']) && $map [] = ['a.user_name', 'like', '%' . $post['user_name'] . '%'];
        isset($post['role']) && $map [] = ['role','=',$post['role']];
        isset($post['market_level']) && $map [] = ['a.market_level','=',$post['market_level']];

        $list = $this->model->page_list($map,$limit, $page);
        return $this->success($list);
    }

    public function add()
    {
        //过滤数据
        $postField = 'pid,user_name,pwd,role,market_level,remarks,invitation_code';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(Admin::class)->scene('add')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        //验证成功，查询是否存在该用户
        $user = $this->model->where('user_name', $post['user_name'])->find();
        if ($user) return $this->failed('该用户以存在');
        //加密密码
        $post['pwd'] = !empty($post['pwd']) && isset($post['pwd']) ? pwdEncryption($post['pwd']) : pwdEncryption(admin_Initial_pwd());
        $post['googlecode'] =generateCode(32,40);
        //插入数据库
        !isset($post['pid']) && $post['pid'] = 0;
        !isset($post['market_level']) && $post['market_level'] = 0;
        $save = false;
        Db::startTrans();
        try {
            //写入角色 并
           $this->model->save($post);
            $this->market(intval($this->model->id), intval($post['pid']),intval($post['market_level']));
            $save = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        if ($save) return $this->success([]);
        return $this->failed('新增失败');
    }

    //写入到 common_market_relation 数据
    public function market(int $userId, int $pid,int $level)
    {
        if ($userId <= 0) return false;
        $db = Db::name('common_market_relation');
        if ($pid >= 1) {
            //查询到当前用户的父级
            $find = $db->where('aid', $pid)->find();
            //获取用户父级信息 插入到数据
            $db->insert(['aid' => $userId, 'a_level' => $level, 'pid' => $find['aid'], 'p_level' => $find['a_level'], 'path' => $find['path'] . ',' . $userId]);
            return true;
        }
        // 新增当前数据
        $db->insert(['aid' => $userId, 'a_level' => $level, 'pid' => 0, 'p_level' => 0, 'path' => $userId]);
        return true;
    }

    /**
     * 获取用户信息
     * @return mixed
     */
    public function detail()
    {
        //过滤数据
        $postField = 'id';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        //验证数据
        try {
            validate(Admin::class)->scene('detail')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        //查询用户数据
        $user = $this->model->find($post['id']);
        if ($user) return $this->success($user);
        return $this->failed('用户不存在');
    }

    /**
     * 修改方法
     * @return mixed
     */
    public function edit()
    {
        //过滤数据
        $postField = 'id,user_name,pwd,role,market_level,remarks';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(Admin::class)->scene('edit')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        //查询是否重复的用户名
        $find = $this->model->where('user_name', $post['user_name'])->where('id', '<>', $post['id'])->find();
        if ($find) return $this->failed('用户已存在');
        !empty($post['pwd']) && $post['pwd'] = pwdEncryption($post['pwd']);
        $post=array_filter($post);
        //执行修改数据
        $save = $this->model->update($post);

        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
     /**
     * 统计
     * */
    public function statistics(){
        $map = [];
        $map_agent = [];
        // 增加 代理商 推广列表
        if (session('admin_user.role')==2) {
            $map = ['b.market_uid' => session('admin_user.id')];
            $map_agent = ['market_uid' => session('admin_user.id')];
        }
        $array=array(); // 计划返回数据
        $day_start = $this->request->post('start', date("Y-m-d",0)); // 默认 从0 开始
        $day_end = $this->request->post('end', date("Y-m-d")); // 到现在 就是 全部数据了

        //总注册量 | 首充 
        // 登录次数
        $UserLogin = new \app\common\model\LoginLog();
        $array['user_login_times']=$UserLogin->alias('a')->join('common_user b', 'a.unique = b.id', 'left')->where($map)->whereBetweenTime('a.login_time',$day_start,$day_end)->count('a.id');
        //echo $UserLogin->getLastSql();
        // 签到次数
        $QianDao = new \app\common\model\TouziQianDao();
        $array['user_qiandao_times']=$QianDao->alias('a')->join('common_user b', 'a.user_id = b.id', 'left')->where($map)->whereBetweenTime('a.create_time',$day_start,$day_end)->count('a.id');

        //注册人数
        $User= new User();
        $array['register_numbers']=$User->where($map_agent)->whereBetweenTime('create_time',$day_start,$day_end)->count('id');
        
        // 产品订单
        $TouziProductOrder=new \app\common\model\TouziProductOrder();
        //购买产品数量
        $array['buy_product_nums']=$TouziProductOrder->alias('a')->join('common_user b', 'a.user_id = b.id', 'left')->where($map)->whereBetweenTime('a.create_time',$day_start,$day_end)->count('a.id');
        //购买产品金额
        $array['buy_product_money']=$TouziProductOrder->alias('a')->join('common_user b', 'a.user_id = b.id', 'left')->where($map)->whereBetweenTime('a.create_time',$day_start,$day_end)->sum('a.buy_price');


        //平台 充值 提现 利润 
        $PayRecharge=new PayRecharge();
        $PayWithdraw=new PayWithdraw();

        // 首充人数
        $array['user_shouchong_times']=$PayRecharge->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.is_first_recharge',1)->whereBetweenTime('a.create_time',$day_start,$day_end)->count('a.id');
        // 后台充值 充值金额总数
        $array['recharge_money_admin_nums'] = $PayRecharge->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.currency_type','local')->where('a.status',1)->where('a.is_admin_action',1)->whereBetweenTime('success_time',$day_start,$day_end)->sum('a.money');//本地
        // 后台提现 提现金额总数
        $array['withdraw_money_admin_nums'] = $PayWithdraw->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.currency_type','local')->where('a.status',1)->where('a.is_admin_action',1)->whereBetweenTime('success_time',$day_start,$day_end)->sum('a.money');//本地
        // 充值金额总数
        $Recharge_money_nums = $PayRecharge->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.currency_type','local')->where('a.status',1)->whereBetweenTime('success_time',$day_start,$day_end)->sum('a.money');//本地
        // 提现金额总数
        $withdraw_money_nums = $PayWithdraw->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.currency_type','local')->where('a.status',1)->whereBetweenTime('success_time',$day_start,$day_end)->sum('a.money');//本地
        // 充值金额
        $array['recharge_money_nums'] = $Recharge_money_nums;
        // 提现金额
        $array['withdraw_money_nums'] = $withdraw_money_nums;
        // 毛利总数
        $array['tprofit']=$Recharge_money_nums - $withdraw_money_nums;
        //充值笔数
        $array['recharge_nums']=$PayRecharge->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.status',1)->whereBetweenTime('success_time',$day_start,$day_end)->count('a.id');
        // 提现笔数
        $array['withdraw_nums']=$PayWithdraw->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.status',1)->whereBetweenTime('success_time',$day_start,$day_end)->count('a.id');
        // 充值人数  Db::name('common_pay_recharge')
        $array['recharge_person_nums']= $PayRecharge->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.status',1)->whereBetweenTime('success_time',$day_start,$day_end)->group('a.uid')->count('a.id');
        // 提现人数
        $array['withdraw_person_nums']= $PayWithdraw->alias('a')->join('common_user b', 'a.uid = b.id', 'left')->where($map)->where('a.status',1)->whereBetweenTime('success_time',$day_start,$day_end)->group('a.uid')->count('a.id');
        
        // 设置谷歌验证码
        // $array['googlecode'] = generateCode();
        // 数据返回
        return $this->success($array);
    }
    
// 类结束了
}